package com.ht.medicaltreatment.fragment

import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.gym.baselib.base.BaseFragment
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.activity.CentrifugeActivity
import com.ht.medicaltreatment.activity.CentrifugeAddSampleActivity
import com.ht.medicaltreatment.activity.CentrifugeDetailActivity
import com.ht.medicaltreatment.activity.CentrifugeParamsSetActivity
import com.ht.medicaltreatment.activity.CentrifugeRecordActivity
import com.ht.medicaltreatment.bean.AllCentrifugeBean
import com.ht.medicaltreatment.bean.CentrifugeDetailBean
import com.ht.medicaltreatment.bean.CentrifugeStateBean
import com.ht.medicaltreatment.utils.DownTimeUtils
import com.ht.medicaltreatment.view.StopCentrifugeDialog
import com.ht.medicaltreatment.viewmodel.CentrifugeMainViewModel
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgAdd
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgContinue
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgDetail
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgOver
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgParams
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgRecord
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgReset
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgStart
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.imgStop
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvAdd
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvAddCount
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvDetail
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvName
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvParams
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvRecord
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvRotationSpeed
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvTem
import kotlinx.android.synthetic.main.fragment_centrifuge_layout.tvTime

//离心机Fragment
class CentrifugeFragment:BaseFragment(), View.OnClickListener {
    override fun getLayoutResId()= R.layout.fragment_centrifuge_layout

    private lateinit var bean:AllCentrifugeBean
    private lateinit var model: CentrifugeMainViewModel
    //未完成的离心机订单
    private lateinit var map: MutableMap<Int, CentrifugeStateBean>
    private var centrifugeId = 0
    private var downTimeDisposable: Disposable? = null
    //离心机剩余时间 秒
    private var downTime = 0
    //原始的离心时间，用来重新离心时，进行倒计时
    private var originalDownTime = 0
    //是否正在离心
    private var isCentrifuge = false

    //离心机中的样本数据
    private val centrifugeSampleMap = mutableMapOf<Int, CentrifugeDetailBean>()

    override fun init() {
        model = (activity as CentrifugeActivity).model
        map = (activity as CentrifugeActivity).map
        imgStart.setOnClickListener(this)
        imgParams.setOnClickListener(this)
        tvParams.setOnClickListener(this)
        imgAdd.setOnClickListener(this)
        tvAdd.setOnClickListener(this)
        imgRecord.setOnClickListener(this)
        tvRecord.setOnClickListener(this)
        imgDetail.setOnClickListener(this)
        tvDetail.setOnClickListener(this)
        imgOver.setOnClickListener(this)
        imgStop.setOnClickListener(this)
        imgReset.setOnClickListener(this)
        imgContinue.setOnClickListener(this)

        val json = arguments?.get("bean") as String
        bean = GsonUtils.fromJson(json,AllCentrifugeBean::class.java)
        if(bean.name.isNotBlank()){
            initData()
        }
    }

    fun changeBean(json:String){
        bean = GsonUtils.fromJson(json,AllCentrifugeBean::class.java)
        initData()
    }

    private fun initData() {
        centrifugeId = bean.id

        LogUtils.i("bean.time: ${bean.time}")

        //无论是否有未完成的订单，都先获取下最开始的倒计时，作为原始时间保存下
        if(bean.time.endsWith("min")){
            val time = bean.time.substring(0,bean.time.length-3)
            val accTime = bean.accTime.substring(0,bean.accTime.length-3)
            val down = bean.downTime.substring(0,bean.downTime.length-3)
            downTime = (time.toFloat() * 60 + accTime.toFloat() * 60 + down.toFloat() * 60).toInt()
            //LogUtils.i(accTime,down,time.toInt() * 60,accTime.toInt() * 60,down.toInt() * 60)
        }else{
            downTime = (bean.time.toFloat() * 60 + bean.accTime.toFloat() * 60 + bean.downTime.toFloat() * 60).toInt()
            //LogUtils.i(bean.time,bean.accTime,bean.downTime)
        }
        originalDownTime = downTime

        tvTime.setText("${downTime*1.0/60}min")

        if(map.containsKey(centrifugeId)){
            val bean = map[centrifugeId]
            bean?.let {
                if(bean.status == 0 && bean.currentCentrifugeSampleNumber > 0 && bean.rediumTime > 0){
                    //有未完成的离心订单
                    //还有剩余时间，继续离心
                    downTime = map[centrifugeId]!!.rediumTime
                    tvTime.setText(DownTimeUtils.getDownTime(downTime))
                    //执行倒计时
                    downTime()
                }else if(bean.status == 0 && bean.rediumTime <= 0){
                    //离心结束，但是没有调用完成离心的接口，需要调用下
                    //完成离心接口
                    completeCentrifuge()
                }else if(bean.status == 1){
                    //离心停止了
                    imgStart.visibility = View.GONE
                    imgReset.visibility = View.VISIBLE
                    imgContinue.visibility = View.VISIBLE

                    isCentrifuge = true
                    isPositive = true
                }
            }
        }

        tvRotationSpeed.setText(bean.rotationRate)
        tvTem.setText(bean.temperate)
        tvName.setText(bean.name)

        sampleData()
    }

    override fun onClick(v: View?) {
        when(v){
            //参数设置
            imgParams,tvParams -> {
                if(isCentrifuge){
                    showToast("正在离心")
                    return
                }
                val intent = Intent(requireContext(), CentrifugeParamsSetActivity::class.java)
                intent.putExtra("name",bean?.name)
                intent.putExtra("brand",bean?.brandModel?.brand)
                intent.putExtra("model",bean?.brandModel?.modelNumber)
                intent.putExtra("accTime",bean?.accTime)//升速时间
                intent.putExtra("downTime",bean?.downTime)//降速时间
                intent.putExtra("centrifugeTime",bean.time.substring(0,bean.time.length-3))
                intent.putExtra("speed",bean.rotationRate)
                intent.putExtra("temperature",bean.temperate)

                intent.putExtra("id",bean?.id)
                startActivityForResult(intent,{
                    LogUtils.i("修改完  ")
                    (activity as CentrifugeActivity).initData()
                })
            }
            //添加样本
            imgAdd,tvAdd -> {
                if(isCentrifuge){
                    showToast("正在离心")
                    return
                }
                val intent = Intent(requireContext(), CentrifugeAddSampleActivity::class.java)
                intent.putExtra("centrifugeId",centrifugeId)
                startActivityForResult(intent){
                    val centrifugalSpeed = it?.getStringExtra("centrifugalSpeed")
                    val centrifugalTemperature = it?.getStringExtra("centrifugalTemperature")
                    val centrifugalTime = it?.getStringExtra("centrifugalTime")

                    //tvRotationSpeed.text = centrifugalSpeed
                    //tvTem.text = centrifugalTemperature
                    (activity as CentrifugeActivity).initData()
                }
            }
            //离心记录
            imgRecord,tvRecord -> {
                val intent = Intent(requireContext(), CentrifugeRecordActivity::class.java)
                intent.putExtra("centrifugeId",centrifugeId)
                startActivity(intent)
            }

            //离心详情
            imgDetail,tvDetail -> {
                if(isCentrifuge){
                    showToast("正在离心")
                    return
                }
                val intent = Intent(requireContext(), CentrifugeDetailActivity::class.java)
                intent.putExtra("centrifugeId",centrifugeId)
                startActivity(intent)
            }

            //开始离心
            imgStart -> {
                if(!isPositive){
                    showToast("请添加样本")
                    return
                }
                showProgress()
                model.saveCentrifugeOrder("$centrifugeId", "$downTime",{
                    dismissProgress()
                    downTime()
                })
            }

            //停止离心,只是前端停止离心了，实际上机器并没有停止，后台的离心倒计时仍然在走
            imgStop -> {
                StopCentrifugeDialog(requireContext()).show {
                    showProgress()
                    LogUtils.i("停止离心：downTime: $downTime")
                    model.stopCentrifuge(TimeUtils.getNowString(),"$downTime","$centrifugeId",{
                        dismissProgress()
                        downTimeDisposable?.dispose()
                        imgReset.visibility = View.VISIBLE
                        imgContinue.visibility = View.VISIBLE
                        imgStop.visibility = View.GONE
                        imgOver.visibility = View.GONE
                    })
                }
            }

            //结束离心
            imgOver -> {
                model.overCentrifuge("$centrifugeId"){
                    imgStart.visibility = View.VISIBLE
                    imgOver.visibility = View.GONE
                    imgStop.visibility = View.GONE
                    tvAddCount.text = "0"
                    isPositive = false
                    downTimeDisposable?.dispose()
                    tvTime.setText("${originalDownTime*1.0/60}min")
                    isCentrifuge = false
                }
            }

            //重新离心
            imgReset -> {
                showProgress()
                model.restartCentrifuge("$centrifugeId"){
                    downTime = originalDownTime
                    model.saveCentrifugeOrder("$centrifugeId","$downTime",{
                        dismissProgress()
                        downTime()
                    })
                }
            }

            //继续离心
            imgContinue -> {
                LogUtils.i("继续离心1：downTime: $downTime")
                model.stopOrStart("$centrifugeId",{ time ->
                    if(time > 0){
                        downTime = time
                        LogUtils.i("继续离心2：downTime: $downTime")
                        downTime()
                    }else{
                        completeCentrifuge()
                    }
                })
            }
        }
    }

    var isPositive = false

    fun sampleData(){
        model.centrifugeInfo("$centrifugeId",{
            it?.let {
                centrifugeSampleMap[centrifugeId] = it
                if (it.centrifugeSampleList == null || it.centrifugeSampleList.size == 0) {
                    tvAddCount.text = "0"
                    isPositive = false
                } else {
                    tvAddCount.text = "${it.centrifugeSampleList.size}"
                    isPositive = true
                }
            }
        })
    }

    private fun downTime() {
        isCentrifuge = true
        imgStart.visibility = View.GONE
        imgOver.visibility = View.VISIBLE
        imgStop.visibility = View.VISIBLE
        imgReset.visibility = View.GONE
        imgContinue.visibility = View.GONE
        LogUtils.i("开始离心downTime: $downTime")
        downTimeDisposable = DownTimeUtils.formatDownTime(downTime,
            //剩余时间 - 倒计时格式
            onProgress = {
                tvTime.text = it
                //LogUtils.i("onProgress $it")
            },
            //剩余时间 - 秒单位
            remainingTime = {
                downTime = it
                //LogUtils.i("剩余时间 $it")
                map[centrifugeId]?.rediumTime = downTime
                if(downTime == 0){
                    completeCentrifuge()
                }
            }
        )
    }

    //完成离心
    fun completeCentrifuge(){
        model.centrifugeState("$centrifugeId",{
            if(bean.time.endsWith("min")){
                val time = bean.time.substring(0,bean.time.length-3)
                downTime = (time.toFloat() * 60).toInt()
            }else{
                downTime = (bean.time.toFloat() * 60).toInt()
            }
            tvTime.setText(bean.time)

            tvAddCount.text = "0"
            isPositive = false
            isCentrifuge = false
            imgStart.visibility = View.VISIBLE
            imgOver.visibility = View.GONE
            imgStop.visibility = View.GONE
            imgReset.visibility = View.GONE
            imgContinue.visibility = View.GONE
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        downTimeDisposable?.dispose()
    }
}